using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Creates and displays a message box.
/// </summary>
public class MessageBox
{
    private static Hashtable ExecutingPages = new Hashtable();

    private MessageBox()
    {
    }

    /// <summary>
    /// Shows a message box.
    /// </summary>
    /// <param name="Message"></param>
    public static void Show(string Message)
    {
        if (!ExecutingPages.Contains(HttpContext.Current.Handler))
        {
            Page ExecutingPage = HttpContext.Current.Handler as Page;
            if (ExecutingPage != null)
            {
                Queue messageQueue = new Queue();
                messageQueue.Enqueue(Message);
                ExecutingPages.Add(HttpContext.Current.Handler, messageQueue);
                ExecutingPage.Unload += new EventHandler(ExecutingPage_Unload);
            }
        }
        else
        {
            Queue Queue = (Queue)ExecutingPages[HttpContext.Current.Handler];
            Queue.Enqueue(Message);
        }
    }

    /// <summary>
    /// Our page has finished rendering so lets output the JavaScript 
    /// to produce the alert's
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ExecutingPage_Unload(object sender, EventArgs e)
    {
        Queue Queue = (Queue)ExecutingPages[HttpContext.Current.Handler];
        if (Queue != null)
        {
            StringBuilder sb = new StringBuilder();
            int MsgCount = Queue.Count;
            sb.Append("<script language='javascript'>");
            string Msg;
            while (MsgCount-- > 0)
            {
                Msg = (string)Queue.Dequeue();
                Msg = Msg.Replace("\n", "\\n");
                Msg = Msg.Replace("\"", "'");
                sb.Append(@"alert( """ + Msg + @""" );");
            }
            sb.Append(@"</script>");
            ExecutingPages.Remove(HttpContext.Current.Handler);
            HttpContext.Current.Response.Write(sb.ToString());
        }
    }
}